package cn.edu.ujn.finaltest.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mysql.jdbc.StringUtils;


import cn.edu.ujn.finaltest.dao.OrderItemMapper;
import cn.edu.ujn.finaltest.dao.Orders;
import cn.edu.ujn.finaltest.dao.OrdersMapper;
import cn.edu.ujn.finaltest.dao.Product;
import cn.edu.ujn.finaltest.util.Page;

@Service
@Transactional
public class OrdersServiceImpl implements IOrdersService{

	@Autowired
	private OrdersMapper orderDao;
	
	@Autowired
	private OrderItemMapper orderItemDao;
	
	@Override
	public int deleteByPrimaryKey(Integer id) {
		// TODO Auto-generated method stub
		int itemDelete = this.orderItemDao.deleteByOrderId(id);
		System.out.println("******删除订单项" + itemDelete);
		int delete = this.orderDao.deleteByPrimaryKey(id);
		return delete;
	}


	@Override
	public Orders selectByPrimaryKey(Integer id) {
		// TODO Auto-generated method stub
		Orders order = orderDao.selectByPrimaryKey(id);
		return order;
	}

	@Override
	public Page<Orders> findOrderList(Integer page, Integer rows, String number, Integer userid) {
		// TODO Auto-generated method stub
		Orders order = new Orders();
		if(!StringUtils.isNullOrEmpty(number)) {
			order.setNumber(number);
		}
		order.setUserid(userid);
		order.setStart((page-1) * rows);
		order.setRows(rows);
		List<Orders> orders = this.orderDao.findAll(order);
		// 查询客户列表总记录数
		Integer count = this.orderDao.selectOrderListCount(order);
		// 创建Page返回对象
		Page<Orders> result = new Page<Orders>();
		result.setPage(page);
		result.setRows(orders);
		result.setSize(rows);
		result.setTotal(count);
		return result;
	}

	@Override
	public Integer selectOrderListCount(Orders order) {
		// TODO Auto-generated method stub
		return this.orderDao.selectOrderListCount(order);
	}


	@Override
	public int insert(Orders row) {
		// TODO Auto-generated method stub
		int insert = orderDao.insertSelective(row);
		if(insert>0) {
			List<Product> productList = row.getProductList();
			for(Product p:productList) {
				Map<String, Integer> orderItem = new HashMap<String, Integer>();
				orderItem.put("order_id", row.getId());
				orderItem.put("product_id",p.getId());
				orderItemDao.addOrderItem(orderItem);
			}
			
		}
		return insert;
	}
}
